import React, { Component } from 'react';
import styled from 'styled-components';
import PropTypes from 'prop-types';
import { FormattedMessage } from 'react-intl';
import { Black, LinkBlue, HoverBlack } from 'style/Color';
import RichTextRender from 'component/RichTexts/RichTextRender';

const Container = styled.div`
  margin-top: 8px;
`;
const Collapsed = styled(Container)`
  cursor: pointer;
`;
const Content = styled.span`
  margin: 0;
  color: ${Black};
  font-size: 15px;
  line-height: 1.6;
  word-break: break-word;
`;
const More = styled.span`
  margin: 0;
  color: ${LinkBlue};
  font-size: 15px;
  line-height: 1.6;
  word-break: break-word;
  :hover {
    color: ${HoverBlack};
  }
`;

const Limit200 = 200;
const Limit5 = 5;

const isTooLongBeginning = blocks => {
  // eslint-disable-next-line no-debugger
  // debugger;
  return blocks.slice(0, Limit5).reduce((total, item) => total + item.text, '').length > Limit200;
};

const isTooMuchBlocks = blocks => {
  return blocks.length > Limit5;
};

// the input row must be too long beginning or too much blocks
const getSlicePosition = blocks => {
  // eslint-disable-next-line no-debugger
  // debugger;

  let position = 0;
  let counts = 0;
  let current;

  const lenLimit = Math.min(Limit5, blocks.length);

  while (position < lenLimit) {
    current = blocks[position]; // current will must exist
    if (counts + current.text.length > Limit200) {
      break;
    }
    counts += current.text.length;
    position += 1;
  }

  return { position, counts };
};

const JSONSafeParse = strings => {
  let json;
  try {
    json = JSON.parse(strings);
  } catch (e) {
    json = {
      blocks: [],
      entityMap: {}
    };
    console.warn('JSONSafeParse:', e);
  }

  return json;
};

class RichTextCollapse extends Component {
  constructor(props) {
    super(props);
    this.state = { collapse: !props.expand, row: JSONSafeParse(props.data) };
    this.expand = this.expand.bind(this);
  }

  expand() {
    const collapse = false;
    this.setState({ collapse });
  }

  render() {
    const { collapse, row } = this.state;
    const { blocks, entityMap } = row;

    if (!collapse) {
      return (
        <Container>
          <RichTextRender data={row} />
        </Container>
      );
    }

    const tooLongBeginning = isTooLongBeginning(blocks);
    const tooMuchBlocks = isTooMuchBlocks(blocks);

    if (!tooLongBeginning && !tooMuchBlocks) {
      return (
        <Container>
          <RichTextRender data={row} />
        </Container>
      );
    }

    const { position, counts } = getSlicePosition(blocks);
    const rowSliced = { blocks: blocks.slice(0, position), entityMap };
    return (
      <Collapsed>
        {position > 0 && <RichTextRender data={rowSliced} />}
        {blocks[position] && blocks[position].type === 'unstyled' && (
          <Content onClick={this.expand}>
            {blocks[position].text.slice(0, Limit200 - counts)}...
          </Content>
        )}
        <More onClick={this.expand}>
          (<FormattedMessage id="view.more" />)
        </More>
      </Collapsed>
    );
  }
}

RichTextCollapse.defaultProps = {
  expand: false
};

RichTextCollapse.propTypes = {
  data: PropTypes.string.isRequired,
  expand: PropTypes.bool
};

export default RichTextCollapse;
